from django.contrib import admin
from django.utils.safestring import mark_safe

from . import models


# 注册文章
class ArticleManager(admin.ModelAdmin):
    list_display = ['title', 'get_image', 'author', 'get_tag', 'update_time', 'create_time']
    search_fields = ['title', 'content']
    list_filter = ['create_time']
    filter_horizontal = ['tag']

    def get_image(self, obj):
        try:
            obj_url = obj.image.url
        except:
            return ''
        return mark_safe('<img src="{url}" width="{width}" height={height} />'
                    .format(url=obj_url, width='70px', height='70px', )
                 )
    get_image.short_description = mark_safe('<div style="color:#409eff">封面<div>')

    def get_tag(self, obj):
        return [item.name for item in obj.tag.all()]

    get_tag.short_description = mark_safe('<div style="color:#409eff">标签<div>')


admin.site.register(models.Article, ArticleManager)


# 注册标签
class TagManager(admin.ModelAdmin):
    list_display = ['name', 'update_time', 'create_time']
    search_fields = ['name']
    list_filter = ['create_time']


admin.site.register(models.Tag, TagManager)
